package com.easylinkin.linkappapi.lobar.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.easylinkin.linkappapi.lobar.dto.WorkTypeDTO;
import com.easylinkin.linkappapi.lobar.entity.UserProject;
import com.easylinkin.linkappapi.lobar.entity.UserRecord;
import com.easylinkin.linkappapi.lobar.entity.WorkType;
import com.easylinkin.linkappapi.lobar.mapper.UserProjectMapper;
import com.easylinkin.linkappapi.lobar.mapper.UserRecordMapper;
import com.easylinkin.linkappapi.lobar.mapper.WorkTypeMapper;
import com.easylinkin.linkappapi.lobar.util.AlicloudWeatherApi;
import com.easylinkin.linkappapi.lobar.util.ProjectTenatUtils;
import com.easylinkin.linkappapi.roster.entity.RailLinkappRosterPersonnel;
import com.easylinkin.linkappapi.roster.mapper.LinkappRosterPersonnelMapper;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.tenant.dto.LinkappTenantDTO;
import com.easylinkin.linkappapi.tenant.entity.LinkappTenant;
import com.easylinkin.linkappapi.tenant.mapper.LinkappTenantMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: kan yuanfeng
 * @Date: 2022/5/30 16:36
 * @Description: 首页
 */
@RestController
@RequestMapping("index")
@Api(tags = "项目班组管理")
public class IndexController {

  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;
  @Autowired
  private LinkappTenantMapper linkappTenantMapper;
  @Autowired
  private UserProjectMapper userProjectMapper;
  @Autowired
  private UserRecordMapper userRecordMapper;
  @Autowired
  private WorkTypeMapper workTypeMapper;
  @Autowired
  private LinkappRosterPersonnelMapper linkappRosterPersonnelMapper;



  /**
   * @Description: 获取项目信息
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @GetMapping("project")
  @ApiOperation("获取项目信息")
  public RestMessage getProject() {
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    return RestBuilders.successBuilder().data(getProjectById(tenantId)).build();
  }

  /**
   * @Description: 获取项目信息
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @GetMapping("projectById/{id}")
  @ApiOperation("获取项目信息")
  public RestMessage getProject(@PathVariable String id) {
    return RestBuilders.successBuilder().data(getProjectById(id)).build();
  }

  private LinkappTenantDTO getProjectById(String id) {
    LinkappTenant query = new LinkappTenant();
    query.setId(id);
    LinkappTenant linkappTenant = linkappTenantMapper.selectLinkappTenant(query);
    LinkappTenantDTO linkappTenantDTO = new LinkappTenantDTO();
    BeanUtils.copyProperties(linkappTenant,linkappTenantDTO);
    //计算剩余工期
    ProjectTenatUtils.calculateSurplusDay(linkappTenantDTO);
    //计算进度
    ProjectTenatUtils.calculateProgress(linkappTenantDTO);
    // 默认武汉建工集团定位
    String lng = "114.158784";
    String lat = "30.488072";
    if (linkappTenantDTO.getLongitude() != null && linkappTenantDTO.getLatitude() != null) {
      lng = linkappTenantDTO.getLongitude();
      lat = linkappTenantDTO.getLatitude();
    }
//    String area = AlicloudWeatherApi.projectAreaToweaterArea(linkappTenantDTO.getProjectArea());
//    JSONObject weather = AlicloudWeatherApi.queryWeatherFromLocation(lat, lng);
//    if (null != weather) {
//      linkappTenantDTO.setWeatherData(weather);
//    }
    //获取总人数
    LambdaQueryWrapper<RailLinkappRosterPersonnel> userProjectQueryWrapper = new LambdaQueryWrapper<>();
    userProjectQueryWrapper.eq(RailLinkappRosterPersonnel::getTenantId,linkappTenant.getId())
            .eq(RailLinkappRosterPersonnel::getWorkStatus,1);
    Integer sum = linkappRosterPersonnelMapper.selectCount(userProjectQueryWrapper);
    linkappTenantDTO.setIn(sum);
    return linkappTenantDTO;
  }

  /**
   * surplusDay
   * = 0 代表“已完工”
   * = 负数 代表“已延期”
   * = 正数 代表“剩余工期”
   * = null 代表数据异常
   */


  /**
   * @Description: 获取项目出勤数据
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @GetMapping("user")
  @ApiOperation("获取项目信息")
  public RestMessage getUser() {
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    //获取总人数
    QueryWrapper<UserProject> userProjectQueryWrapper = new QueryWrapper<>();
    userProjectQueryWrapper.eq("tenant_id_",tenantId)
        .eq("status_",1);
    Integer sum = userProjectMapper.selectCount(userProjectQueryWrapper);

    QueryWrapper<UserRecord> userRecordQueryWrapper = new QueryWrapper<>();
    userRecordQueryWrapper.eq("tenant_id_",tenantId)
        .ge("record_time_",DateUtil.beginOfDay(new Date()))
        .le("record_time_",DateUtil.endOfDay(new Date()));
    Integer onNum = userRecordMapper.selectCount(userRecordQueryWrapper);
    Map<String, Object> map = new HashMap<>();
    map.put("sum",sum);
    map.put("onNum",onNum);
    return RestBuilders.successBuilder().data(map).build();
  }

  /**
   * 获取工种数据
   */
  @GetMapping("workType")
  @ApiOperation("获取工种数据")
  public RestMessage getWorkTypeDTOs() {
    QueryWrapper<WorkType> queryWrapper = new QueryWrapper<>();
    queryWrapper.orderByAsc("id");
    List<WorkType> workTypeList = workTypeMapper.selectList(queryWrapper);
    //查询顶级
    List<WorkType> types = workTypeList.stream()
        .filter(w -> Integer.valueOf(0).equals(w.getParentId()))
        .collect(Collectors.toList());
    List<WorkTypeDTO> workTypeDTOS = getWorkTypeDTOs(types);
    getChildren(workTypeList,workTypeDTOS);
    return RestBuilders.successBuilder().data(workTypeDTOS).build();
  }

  /**
   * 设置其子工种
   * @param workTypeList
   * @param types
   */
  private void getChildren(List<WorkType> workTypeList, List<WorkTypeDTO> types) {
    types.forEach(t ->{
      List<WorkType> children = workTypeList.stream().filter(w -> w.getParentId().equals(t.getId()))
          .collect(Collectors.toList());
      if (children.size() > 0){
        List<WorkTypeDTO> workTypeDTOs = getWorkTypeDTOs(children);
        t.setChildren(workTypeDTOs);
        this.getChildren(workTypeList,t.getChildren());
      }
    });
  }

  /**
   * 数据转换
   * @param types
   * @return
   */
  private List<WorkTypeDTO> getWorkTypeDTOs(List<WorkType> types) {
    List<WorkTypeDTO> list = new ArrayList<>();
    types.forEach(t ->{
      WorkTypeDTO workTypeDTO = new WorkTypeDTO();
      workTypeDTO.setId(t.getId());
      workTypeDTO.setLabel(t.getName());
      workTypeDTO.setValue(t.getName());
      workTypeDTO.setText(t.getName());
      list.add(workTypeDTO);
    });
    return list;
  }
}
